<template>
    <div class="hand-select-test">
        <el-row :gutter="15">
            <el-col class="categorys" :sm="12" :md="4" :lg="4">
                <!-- 分类 -->
                <el-tree
                    class="filter-tree"
                    :data="categorys"
                    :props="defaultProps"
                    @node-click="categoryClick"
                    default-expand-all
                    node-key="id"
                ></el-tree>
            </el-col>
            <el-col class="list" :sm="24" :md="18" :lg="20">
                <!-- -------------------------------------------------------------------- -->
                <div class="pull-right margin-left">
                    <span class="margin-right">试题类型:</span>
                    <el-select v-model="dataForm.testType">
                        <el-option
                            v-for="(value, key) in testType"
                            :key="key"
                            :value="key"
                            :label="value"
                        ></el-option>
                    </el-select>
                </div>
                <!-- 表格 -->
                <div class="paper-contet">
                    <el-table
                        ref="handSelectTest_multipleTable"
                        tooltip-effect="dark"
                        :data="tableData"
                        style="width:100%"
                        height="500"
                        @selection-change="handleSelectionChange"
                        @row-click="handleRowClick"
                         v-loading="loading"
                    >
                        <template slot="empty">
                            <div>
                                <b>
                                    <i>{{ activeCategoryName }}</i>
                                </b>
                                &nbsp;这个分类的
                                <b>
                                    <i>{{ testType[dataForm.testType] }}</i>
                                </b>
                                &nbsp;还没有试题
                            </div>
                        </template>
                        <!--  :empty-text="activeCategoryName + '分类没有数据'" -->
                        <!-- 选择框  -->
                        <el-table-column type="selection" width="40"></el-table-column>
                        <el-table-column type="index" column-key="index"></el-table-column>
                        <el-table-column
                            prop="qstStem"
                            label="试题标题"
                            sortable
                            header-align="center"
                            align="center"
                            :show-overflow-tooltip="true"
                        >
                            <template slot-scope="scope">
                                <p v-html="delHtmlTag(scope.row.qstStem)"></p>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="difficult"
                            label="试题难度"
                            width="100"
                            :filters="[{ text: '简单', value: 1 }, { text: '一般', value: 2 }, { text: '困难', value:3}]"
                            :filter-method="filterdifficult"
                            filter-placement="bottom-end"
                        >
                            <template slot-scope="scope">
                                <el-tag
                                    :type="scope.row.difficult === 1 ? 'primary' : ((scope.row.difficult === 2) ? 'success' :  'info')"
                                    disable-transitions
                                >{{difficultLabel[scope.row.difficult - 1]}}</el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column prop="score" label="分数" sortable width="70"></el-table-column>
                        <el-table-column label="详细内容" width="80">
                            <template slot-scope="scope">
                                <el-popover
                                    :width="500"
                                    placement="top-end"
                                    title="详细内容"
                                    trigger="click"
                                >
                                    <TestDeatil :test="scope.row"/>
                                    <el-button slot="reference" type="primary" plain>
                                        <i class="el-icon-view"></i>
                                    </el-button>
                                </el-popover>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 表格结束 -->
            </el-col>
        </el-row>
        <!-- ---------------------------------------------------------------------------------- -->
        <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 15,20, 40, 50, 70, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <div class="pull-right">
            <el-button @click="$emit('closeCurrDialog')" type="info" plain>取消</el-button>
            <el-button
                type="primary"
                plain
                @click="testCheckedUpdate(); $emit('handleConfirm', selectTestContent); multipleTableDefaultSelectCheckbox();"
            >确定</el-button>
        </div>
    </div>
</template>


<script>
import TestDeatil from "@/components/test-detail";
export default {
    components: { TestDeatil },
    props: {
        courseId: Number,
        selectTestContent: Object
        // selectTestContent: {
        //     qst_single: [],
        //     qst_more: []
        //         // 试题id： {试题}
        //     ]
        // }
    },
    data() {
        return {
            categorys: [],
            tableData: [],
            defaultProps: {
                children: "children",
                label: "name"
            },
            activeCategoryName: "",
            multipleSelection: [],
            dataForm: {
                selectCategoryId: "",
                testType: "qst_single" // 当前激活的试题类型
            },
            testType: {
                qst_single: "单项选择题",
                qst_more: "多项选择题",
                qst_judge: "判断题",
                qst_gap_fillging: "填空题",
                qst_design: "问答题"
            },
            totalPage: 0,
            pageIndex: 1,
            pageSize: 20,
            difficultLabel: ["简单", "一般", "困难"],
            currTableOldTestSelectContent: [], // 当前table旧的选择的内容
            oldSelectTestType: "qst_single", // 选择旧的试题类型
            loading: true
        };
    },
    watch: {
        "dataForm.testType": function(currValue, olaValue) {
            this.oldSelectTestType = olaValue;
            this.pageIndex = 1;
            this.getTest();
        }
    },
    created() {
        this.$http("/api/category/get", {
            params: {
                course: this.courseId
            }
        })
            .then(({ data }) => {
                if (data.code === 0) {
                    this.categorys = data.data;
                    this.dataForm.selectCategoryId = data.data[0].id;
                    this.activeCategoryName = data.data[0].name;
                } 
                this.loading = false
            })
            .catch(err => {
                this.$message.error("获取分类列表失败");
                this.loading = false
            });
    },
    methods: {
        // 每页数
        sizeChangeHandle(val) {
            this.pageSize = val;
            this.pageIndex = 1;
            this.getTest();
        },
        // 当前页
        currentChangeHandle(val) {
            this.pageIndex = val;
            this.getTest();
        },
        //   分类点击
        categoryClick(currObj, currNode, vueComponent) {
            if (currNode.isLeaf) {
                // console.log("currObj", currObj);
                this.oldSelectTestType = this.dataForm.testType;
                this.dataForm.selectCategoryId = currObj.id;
                this.activeCategoryName = currObj.name;
                this.getTest();
            }
        },
        // 得到试题
        getTest() {
            if (!this.dataForm.selectCategoryId) return;
            if (this.loading) return;
            this.loading = true;
            this.$http("/api/question/list", {
                params: {
                    categoryId: this.dataForm.selectCategoryId,
                    tName: this.dataForm.testType,
                    page: this.pageIndex,
                    limit: this.pageSize
                }
            })
                .then(({ data }) => {
                    this.testCheckedUpdate();
                    // console.log("data", data);
                    this.tableData = [];
                    if (data.code === 0) {
                        this.tableData = data.page.list;
                        this.totalPage = data.page.totalCount;
                    } else {
                        this.tableData = [];
                        this.totalPage = 0;
                    }
                    this.loading = false;
                    this.$nextTick(function() {
                        this.multipleSelection = [];
                        this.multipleTableDefaultSelectCheckbox();
                    });
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        // 困难度过滤
        filterdifficult(value, row) {
            return row.difficult === value;
        },
        //点击复选框触发，复选框样式的改变
        handleSelectionChange(val) {
            this.multipleSelection = val;
            /*let selectContent = this.selectTestContent[this.dataForm.testType];
            if (!selectContent || selectContent.length < 1) {
                selectContent = val;
            } else {
                for (let i = 0; i < val.length; i++) {
                    for (let j = 0; j < selectContent.length; j++) {
                        // 是否可以添加
                        if (selectContent[j].id == val[i].id) {
                            break;
                        } else if (j === selectContent.length - 1) {
                            selectContent.push(val[i]);
                        }
                    }
                }
            }
            this.selectTestContent[this.dataForm.testType] = selectContent;*/
        },
        //点击行触发，选中或不选中复选框
        handleRowClick(row, column, event) {
            if (column.label == "详细内容") return;
            this.$refs.handSelectTest_multipleTable.toggleRowSelection(row);
            // console.log("this.selecTestContent", this.selectTestContent);
        },
        // 默认选中
        multipleTableDefaultSelectCheckbox() {
            let selectContent = this.selectTestContent[this.dataForm.testType];
            this.currTableOldTestSelectContent = [];
            if (selectContent && selectContent.length > 0) {
                this.tableData.forEach((item, index) => {
                    selectContent.forEach(selectItem => {
                        if (item.id == selectItem.id) {
                            this.currTableOldTestSelectContent.push(item);
                            /**
                             * 在这里还必须是 tableData[index]的数据， 是 selectItem的数据都不行
                             */
                            this.$refs.handSelectTest_multipleTable.toggleRowSelection(
                                this.tableData[index],
                                true
                            );
                        }
                    });
                });
            }
        },
        testCheckedUpdate() {
            this.oldTestToNewTestDel();
            this.newTestToOldTestAdd();
        },
        // 从原来的试题中 ==> 新的试题， 如果如果原来的不存在了 进行删除
        oldTestToNewTestDel() {
            let T_old = JSON.parse(JSON.stringify(this.currTableOldTestSelectContent));
            if (T_old.length < 1) return;
            let T_new = JSON.parse(JSON.stringify(this.multipleSelection));
            console.log('T_old', T_old)
            console.log('T_new', T_new)
            for (let i = 0; i < T_old.length; i++) {
                if (T_new.length < 1) {
                    this.delOldTest(T_old[i]);
                } else {
                    let isExist = false;
                    for (let j = 0; j < T_new.length; j++) {
                        // 存在
                        if (T_old[i].id == T_new[j].id) {
                            isExist = true
                            break;
                        }
                        // 不存在
                        else if (j === T_new.length - 1 && !isExist) {
                            this.delOldTest(T_old[i]);
                        }
                    }
                }                
            }
        },
        // 从新的的试题中 ==> 旧的试题， 从头到尾旧的试题都没有的话 进行添加
        newTestToOldTestAdd() {
            let T_old = JSON.parse(JSON.stringify(this.currTableOldTestSelectContent));
            let T_new = JSON.parse(JSON.stringify(this.multipleSelection));
            if(T_new.length < 1) return;
            if (T_old.length < 1) {
               
                if (
                    !this.selectTestContent[this.oldSelectTestType] ||
                    this.selectTestContent[this.oldSelectTestType].length < 1
                ) {
                    this.selectTestContent[this.oldSelectTestType] = []
                }
                this.selectTestContent[this.oldSelectTestType] = this.selectTestContent[this.oldSelectTestType].concat(T_new);
                return;
            }

            for (let i = 0; i < T_new.length; i++) {
                let isExist = false;
                for (let j = 0; j < T_old.length; j++) {
                    // 存在
                    if ( T_new[i].id == T_old[j].id) {
                        isExist = true
                        break;
                    }                    
                    // 不存在
                    else if (j === T_old.length - 1 && !isExist) {
                        this.selectTestContent[this.oldSelectTestType].push(T_new[i]);
                    }
                }
            }
            // console.log('this.selectTestContent[this.oldSelectTestType]', this.selectTestContent[this.oldSelectTestType])
        },
        // 删除旧试题
        delOldTest(row) {
            if (typeof row !== "object") return;
            let selectContent = this.selectTestContent[this.oldSelectTestType];
            console.log('>>>>>>>>>>>>>>>>selectContent', selectContent)
            if (!selectContent)return;
            let len = selectContent.length
            for (let i = 0; i < len; i++) {
                if (row.id === selectContent[i].id) {
                    // delete selectContent[i];
                    selectContent.splice(i, 1)
                    break;
                }
            }
            this.selectTestContent[this.oldSelectTestType] = selectContent;
        }
    }
};
</script>

<style lang="scss">
.hand-select-test {
    .categorys {
        .is-current {
            background: #f5fbf9;
        }
    }

}
</style>

